namespace MicroCloud.CodeGenerator.Views.Projects
{
    [MapTo(typeof(CodeProjectTemplateInDto))]
    public class ProjectTemplateViewModel : Screen
    {
        private readonly IServiceProvider _provider;

        public ProjectTemplateViewModel(IModelValidator<ProjectTemplateViewModel> validator, IServiceProvider provider)
           : base(validator)
        {
            _provider = provider;
            Validate();
        }

        public Guid Id { get; set; }

        public bool IsLocked { get; set; }

        public Guid ProjectId { get; set; }

        public Guid TemplateId { get; set; }

        public string TemplateName { get; set; }

        public int Order { get; set; }

        public TemplateViewModel Template { get; set; }

        public IObservableCollection<TemplateViewModel> TemplateSource { get; set; } = new BindableCollection<TemplateViewModel>();

        public void TemplateChange(SelectionChangedEventArgs args)
        {
            if (args.AddedItems.Count > 0 && args.AddedItems[0] is TemplateViewModel template)
            {
                TemplateId = template.Id;
                TemplateName = template.Name;
            }
        }

        public async void Delete()
        {
            if (MessageBox.Show($"是否删除模板“[{TemplateName}]”?", "请确认", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
            {
                return;
            }

            if (Id == Guid.Empty)
            {
                ProjectTemplateListViewModel lstViewModel = IoC.Get<ProjectTemplateListViewModel>();
                var emptyEntities = lstViewModel.ProjectTemplates.ToList().Where(a => a.Id == default);
                lstViewModel.ProjectTemplates.RemoveRange(emptyEntities);
                return;
            }

            OperationResult result = null;
            await _provider.ExecuteScopedWorkAsync(async provider =>
            {
                IDataContract contract = provider.GetRequiredService<IDataContract>();
                result = await contract.DeleteCodeProjectTemplates(Id);
            });
            Helper.Notify(result);
            if (!result.Succeeded)
            {
                return;
            }

            ProjectTemplateListViewModel list = IoC.Get<ProjectTemplateListViewModel>();
            list.Init();
        }
    }

    public class ProjectTemplateViewModelValidator : AbstractValidator<ProjectTemplateViewModel>
    {
        public ProjectTemplateViewModelValidator()
        {
            RuleFor(m => m.TemplateName).NotEmpty().WithMessage("请选择模板");
        }
    }
}
